package win.larryzeal.spring.theme.config;

import org.springframework.core.env.AbstractEnvironment;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.nio.charset.StandardCharsets;
import java.util.EnumSet;

/**
 * 基于spring mvc 4 的注解配置，初始化上下文容器
 * 完全可以实现 WebApplicationInitializer(代替 Web.xml)
 * Created by 张少昆 on 2017/8/25 0025.
 */
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException{
		// TODO 设置默认环境为开发环境(development，test，production)
		servletContext.setInitParameter(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, "development");

		// 设置存活时间半小时，单位为秒
		servletContext.getSessionCookieConfig().setMaxAge(60 * 60);
		// Session监听器
		// servletContext.addListener(new HttpSessionEventPublisher());

		//  *************** 解决编码问题 ***************
		CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
		encodingFilter.setEncoding(StandardCharsets.UTF_8.displayName());
		encodingFilter.setForceEncoding(true);
		FilterRegistration.Dynamic encodingFilterRegistration = servletContext.addFilter("encodingFilter", encodingFilter);
		encodingFilterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC), false, "/*");


		super.onStartup(servletContext);
	}

	/**
	 * 应用上下文，除web部分
	 */
	@Override
	protected Class<?>[] getRootConfigClasses(){
		// 加载配置文件类(@Configuration注解进行标注的文件)
		return new Class<?>[]{
				AppConfig.class
		};
	}

	/**
	 * Web上下文
	 */
	@Override
	protected Class<?>[] getServletConfigClasses(){
		return new Class<?>[]{MvcConfig.class};
	}

	/**
	 * 相当于配置 DispatcherServlet 的 url-pattern
	 */
	@Override
	protected String[] getServletMappings(){
		return new String[]{"/"};
	}


}
